import os
import subprocess
import shutil
import json
import argparse

def get_file_details(file_path):
    result = subprocess.run(['python', '../module/m01_file_detail.py', file_path], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode != 0:
        print(f"Error running m01_file_detail.py for file {file_path}: {result.stderr.decode()}")
        return {"error": "Failed to get file details"}
    try:
        return json.loads(result.stdout)
    except json.JSONDecodeError as e:
        print(f"Invalid JSON output from m01_file_detail.py for file {file_path}: {e}")
        return {"error": "Invalid JSON output"}

def query_db_for_file(db_folder, db_filename, table_name, file_hash):
    result = subprocess.run(['python', '../module/m02_query_file.py', db_folder, db_filename, table_name, file_hash], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    if result.returncode != 0:
        print(f"Error running m02_query_file.py for hash {file_hash}: {result.stderr.decode()}")
        return {"error": "Database query failed"}
    try:
        return json.loads(result.stdout)
    except json.JSONDecodeError as e:
        print(f"Invalid JSON output from m02_query_file.py for hash {file_hash}: {e}")
        return {"error": "Invalid JSON output"}

def main(db_dir, scan_dir, del_dir):
    for root, _, files in os.walk(scan_dir):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            # Get file details
            file_details = get_file_details(file_path)
            if "error" in file_details:
                continue
            
            hash_value = file_details.get("hash")
            size = file_details.get("size")

            if not hash_value or not size:
                print(f"Failed to retrieve hash or size for file {file_path}")
                continue

            # Query database
            db_result = query_db_for_file(db_dir, 'file_hash.db', 'video_hash', hash_value)
            if "error" in db_result:
                continue
            
            absolute_path_in_db = db_result.get("absolute_path")
            if not absolute_path_in_db:
                print(f"No matching entry found in database for file {file_path}")
                continue

            # Check if file sizes match
            db_file_info = get_file_details(absolute_path_in_db)
            print(f"db_file_info is {db_file_info}")
            if db_file_info.get("size") == size and db_file_info.get("hash") == hash_value:
                # Compute the relative path of the file with respect to scan_dir
                rel_path = os.path.relpath(root, scan_dir)
                dest_dir = os.path.join(del_dir, rel_path)
                
                # Create the destination directory if it doesn't exist
                os.makedirs(dest_dir, exist_ok=True)
                
                # Move the file to the corresponding directory structure in del_dir
                dest_path = os.path.join(dest_dir, file_name)
                shutil.move(file_path, dest_path)
                print(f"File {file_path} successfully moved to {dest_path}")
            else:
                print(f"Check failed - file {file_path} does not match with {absolute_path_in_db}:")
                print(f"Filename: {file_name}, File Size: {size}, Hash Value: {hash_value}")
                print(f"Database filename: {os.path.basename(absolute_path_in_db)}, File Size: {db_file_info.get('size')}, Hash Value: {db_file_info.get('hash')}")

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Video file removal tool')
    parser.add_argument('--db', required=True, help='SQLite database and base folder directory A')
    parser.add_argument('--scan-dir', required=True, help='Directory B to scan for files')
    parser.add_argument('--del-dir', required=True, help='Directory C where files will be moved for deletion')

    args = parser.parse_args()
    
    main(args.db, args.scan_dir, args.del_dir)

#e.g. python .\video_remove.py --db D:\video\ --scan-dir D:\video_tmp --del-dir D:\video_del